const { Salesmans } = require('../models/salesmansModel');
const jwt = require('jsonwebtoken');
const { TOKEN_KEY } = require('../ulities/consts');

//销售员登录
async function salesmanLogin(req, res) {
  const { userName, password } = req.body;
  const data = await Salesmans.find({
    userName,
    password,
  });
  if (data.length > 0) {
    const loginer = {
      _id: data[0]._id,
      userName: data[0].userName,
    };
    const token = jwt.sign({
        userName,
      }, // 保存用户信息
      TOKEN_KEY, // 编码字符串
      {
        expiresIn: 60 * 1440,
      } // token 有效期(数字单位:s)
    );
    res.send({
      message: '销售员登录成功',
      status: 1,
      token,
      loginer,
    });
  } else {
    res.send({
      message: '销售员登录失败',
      type: 'LOGIN_FAILED',
      status: 0,
    });
  }
}

async function getAllSalesmans(req, res) {
    const data = await Salesmans.find()
    res.send({
        status: 1,
        data,
        message: '获取销售员成功'
    })
};

async function addOneSalesman(req, res) {
  const { userName, password, phone } = req.body;
  await Salesmans.create({ userName, password, phone });
  res.send({
    status: 1,
    message: '新增销售员成功',
  });
}

async function getOneSalesman(req, res) {
  const { _id } = req.body;
  const data = await Salesmans.findById(_id);
  res.send({
    status: 1,
    message: '获取销售员信息成功',
    data
  })
};

async function updateOneSalesman(req, res) {
  const { _id, userName, password, phone } = req.body;
  const data = await Salesmans.updateOne({ _id }, { userName, password, phone });
  if (data.nModified == 1) {
    res.send({
      status: 1,
      message: '修改销售员成功'
    })
  } else {
    res.send({
      status: 0,
      message: '修改销售员失败'
    })

  }
};

async function updatePasswordSalesman(req, res) {
  const { _id, userName, newPassword, phones } = req.body
  const password = newPassword
  const phone = phones
  const data = await Salesmans.updateOne({ _id }, { userName, password, phone });
  if (data.nModified == 1) {
    res.send({
      status: 1,
      message: '修改密码成功'
    })
  } else {
    res.send({
      status: 0,
      message: '修改密码失败',
    })

  }
}

async function deleteOneSalesman(req, res) {
  const { _id } = req.body;
  await Salesmans.findByIdAndDelete(_id);
  res.send({
    status: 1,
    message: '删除销售员信息成功',
  });
}


//暴露  每个功能
module.exports = { salesmanLogin, getAllSalesmans, addOneSalesman, getOneSalesman, updateOneSalesman, deleteOneSalesman, updatePasswordSalesman }